package com.macro.mall.controller.base;


import com.macro.mall.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xq
 * @desc 获取当前的登录用户信息
 */
@Slf4j
public class BaseAdminController {

    //这个request 是线程安全的
    //其实是从 RequestContextHolder.currentRequestAttributes().getRequest() 得到真正的request，
    // RequestAttributes又是 ThreadLocal的，所以是线程安全的
    @Resource
    protected HttpServletRequest request;

    @Resource
    public HttpServletResponse response;

    @Resource
    protected JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    public HttpServletRequest getRequest() {
        return request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public String getUserId() {
        String authHeader = getRequest().getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
            return jwtTokenUtil.getUserIdFromToken(authToken);
        }
        return null;
    }

}
